#include "TexturedVertexBuffer.h"
#include "..\utils\Log.h"

namespace ds {

TexturedVertexBuffer::TexturedVertexBuffer(D3DPRIMITIVETYPE primitiveType,uint32 maxVertices,bool dynamic) 
	: VertexBuffer(primitiveType,dynamic) , m_MaxVertices(maxVertices) {
	m_FVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE | D3DFVF_TEX1;	
	m_vertexSize = sizeof(TexturedVertex);
	IDirect3DDevice9 * pDevice = gEngine->getDevice();
	D3DPOOL pool = m_Dynamic ? D3DPOOL_DEFAULT : D3DPOOL_MANAGED; 
	DWORD usage = m_Dynamic ? D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC : D3DUSAGE_WRITEONLY; 		
	LOG(logINFO) << "creating new textured vertext buffer size: " << m_MaxVertices << " dynamic: "<< dynamic;
	HR(pDevice->CreateVertexBuffer( m_MaxVertices * sizeof( TexturedVertex),usage,m_FVF ,pool, &vertexBuffer, NULL ));
}

TexturedVertexBuffer::~TexturedVertexBuffer() {
	Release();
}

void TexturedVertexBuffer::addVertex(float x,float y,float z,float u,float v) {
	if ( m_Vertices.size() <= m_MaxVertices ) {
		TexturedVertex tv;
		tv.x = x;
		tv.y = y;
		tv.z = z;
		tv.tu = u;
		tv.tv = v;	
		tv.color = Color(1.0f,1.0f,1.0f,1.0f);
		m_Vertices.push_back(tv);
	}
	else {
		LOG(logERROR) << "TexturedVertexBuffer - addVertex : maximum exceeded";
	}
}

void TexturedVertexBuffer::addVertex(float x,float y,float z,float nx,float ny,float nz,float u,float v) {
	if ( m_Vertices.size() <= m_MaxVertices ) {
		TexturedVertex tv;
		tv.x = x;
		tv.y = y;
		tv.z = z;
		tv.nx = nx;
		tv.ny = ny;
		tv.nz = nz;
		tv.tu = u;
		tv.tv = v;	
		tv.color = Color(1.0f,1.0f,1.0f,1.0f);
		m_Vertices.push_back(tv);
	}
	else {
		LOG(logERROR) << "TexturedVertexBuffer - addVertex : maximum exceeded";
	}
}

void TexturedVertexBuffer::clear() {
	m_Vertices.clear();
}

bool TexturedVertexBuffer::createBuffer() {	
	size_t total = m_Vertices.size();	
	if ( total > 0 ) {		
		TexturedVertex *pVertices;
		HR(vertexBuffer->Lock( 0, 0, ( void** )&pVertices, 0 ));	
		for ( size_t i = 0; i < total; ++i ) {		
			pVertices->x = m_Vertices[i].x;
			if ( gEngine->getRenderMode() == RM_2D ) {
				pVertices->y = gEngine->getHeight() - m_Vertices[i].y;
			}
			else {
				pVertices->y = m_Vertices[i].y;
			}
			pVertices->z = m_Vertices[i].z;
			pVertices->nx = m_Vertices[i].nx;
			pVertices->ny = m_Vertices[i].ny;
			pVertices->nz = m_Vertices[i].nz;
			pVertices->color = m_Vertices[i].color;	
			pVertices->tu = m_Vertices[i].tu;
			pVertices->tv = m_Vertices[i].tv;									
			pVertices++;
		}
		HR(vertexBuffer->Unlock());
	}
	m_numVertices = total;
	return true;
}

};

